<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<head>
	<th:block th:include="include :: header('新增商品')" />
	<th:block th:include="include :: bootstrap-fileinput-css" />
	<th:block th:include="include :: summernote-css" />
	<th:block th:include="include :: bootstrap-select-css" />
	<style>
		.modal-content {
			z-index: 30000;
		}

		.layui-layer.layui-layer-dialog {
			z-index: 99999999 !important;
		}

		.file-preview-success.is-selected {
			border: 1px solid #f30;
		}

		.file-preview-success.is-selected:after {
			content: '默认图';
			width: 60px;
			height: 20px;
			line-height: 20px;
			text-align: center;
			background-color: #f30;
			color: #fff;
			position: absolute;
			left: 0;
			top: 0;
		}
		/**
       商品规格样式
       */

		.ws-goodsstyle__panel {
			border: 1px solid #DAE3E6;
			background: #F5F8FA;
			margin-left: 15px;
		}

		.ws-goodsstyle__panel .tit {
			margin: 5px;
			font-weight: bold;
			clear: both;
		}

		.ws-goodsstyle__panel li {
			float: left;
		}

		.ws-goodsstyle__panel li:not(.tit) {
			background: #f9f9f9;
			border: 1px solid #a9a9a9;
			padding: 2px 5px;
			/*margin: 5px;*/
			margin-left: 8px;
		}
	</style>
</head>

<body class="white-bg">
	<div class="wrapper wrapper-content animated fadeInRight ibox-content">
		<form class="form-horizontal" id="form-goods-add">
			<input id="goodsId" name="goodsId" type="hidden">
			<input name="catId" type="hidden" id="treeId" />
			<input name="typeId" type="hidden" id="typeId" />
			<input id="imageDefaultId" type="hidden" name="imageDefaultId" class="input-large"> <br>
			<input id="imageIds" type="hidden" name="imageIds" class="input-large">
			<h4 class="form-header h4">基本信息</h4>
			<div class="row">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label"><span style="color: red; ">*</span>商品名称：</label>
						<div class="col-sm-9">
							<input type="text" name="name" class="form-control" placeholder="请输入商品名称" maxlength="30"
								required>
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label"><span style="color: red; ">*</span>分类：</label>
						<div class="col-sm-8">
							<div class="input-group">
								<input name="catName" onclick="selectGoodsTree()" id="treeName" type="text"
									placeholder="请选择归属分类" class="form-control" required>
								<span class="input-group-addon"><i class="fa fa-search"></i></span>
							</div>
						</div>
					</div>
				</div>

			</div>

			<div class="row">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label"><span style="color: red; ">*</span>类型：</label>
						<div class="col-sm-9">
							<input id="typeName" type="text" name="typeName" readonly class="form-control" required
								placeholder="请输入类型">
						</div>
					</div>
				</div>

				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label">品牌：</label>
						<div class="col-sm-9">
							<select name="brandId" data-role="brand" class="form-control noselect2 selectpicker"
								data-none-selected-text="请选择品牌" data-live-search="true">
							</select>
						</div>
					</div>
				</div>
			</div>

			<div class="col-md-12" style="margin-left: -160px">
				<div class="form-group">
					<label class="col-sm-3 control-label">商品相册：</label>
					<div class="col-sm-9">
						<input id="goodsPicture" name="file" type="file" multiple>
					</div>
				</div>
			</div>


			<!--<div class="hr-line-dashed"></div>-->
			<div id="goodsBasic">

				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>销售价：</label>
							<div class="col-sm-9">
								<input type="text" id="price" name="price" class="form-control" placeholder="请输入商品价格"
									maxlength="30" required>
							</div>
						</div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>货号：</label>
							<div class="col-sm-9">
								<input type="text" name="bn" id="bn" class="form-control" placeholder="请输入商品货号"
									required>
							</div>
						</div>
					</div>
				</div>

				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>库存：</label>
							<div class="col-sm-9">
								<input type="text" name="store" id="store" class="form-control" placeholder="请输入商品库存"
									maxlength="10" required>
							</div>
						</div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">货位：</label>
							<div class="col-sm-9">
								<input type="text" name="storePlace" id="storePlace" class="form-control"
									placeholder="请输入商品货位" required>
							</div>
						</div>
					</div>
				</div>

			</div>


			<div class="row" id="specBtn" style="display: none">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label"><button id="btnAdd" type="button"
								class="btn btn-primary btn-xs">开启规格</button></label>
						<label class="col-sm-7 control-label"><span
								style="color: red; ">开启规格前先填以上价格等信息，可自动复制信息到货品</span></label>
					</div>
				</div>

			</div>

			<div class="row" id="specDiv" style="display: none">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label"><button type="button"
								class="btn btn-primary btn-xs hidden" id="btnEdit"
								data-role="product-edit">编辑规格</button></label>
						<div class="ws-goodsstyle__panel col-sm-6">
							<ul class="" data-role="spec-item">
								<li class="tit">已经启动的规格项:</li>
								<li>11</li>
								<li>11</li>
							</ul>
							<p class="tit" data-role="spec-tit">
								已生成货品(6)
							</p>
						</div>
						<label class="col-sm-3 control-label"><button type="button" class="btn btn-default btn-xs"
								id="btnClose" data-role="product-close">关闭</button></label>
					</div>
				</div>

			</div>
			<input name="specDesc" id="specDesc" type="hidden">


			<div class="hr-line-dashed">扩展属性</div>
			<div class="hide1" id="propsDiv">
			</div>

			<div class="hr-line-dashed"></div>

			<div class="row">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label">重量：</label>
						<div class="col-sm-9">
							<input type="text" name="weight" value="0" class="form-control" placeholder="请输入商品重量"
								maxlength="10" required>
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label">积分：</label>
						<div class="col-sm-9">
							<input type="text" name="score" class="form-control" placeholder="请输入积分">
						</div>
					</div>
				</div>
			</div>


			<div class="row">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label">商品简介：</label>
						<div class="col-sm-9">
							<textarea name="brief" class="form-control" placeholder="简短的商品介绍,请不要超过70个字"></textarea>
						</div>
					</div>
				</div>
			</div>

			<div class="hr-line-dashed"></div>

			<div class="row">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label">立即上架：：</label>
						<div class="col-sm-9">
							<input type="radio" checked="" value="true" id="optionsRadios1" name="marketable"> 是 &nbsp;
							<input type="radio" checked value="false" id="optionsRadios2" name="marketable"> 否 &nbsp;
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label">增加库存自动上架：</label>
						<div class="col-sm-9">
							<input type="radio" checked="" value="1" id="optionsRadios3" name="isAuto"> 是 &nbsp;
							<input type="radio" checked value="2" id="optionsRadios4" name="isAuto"> 否 &nbsp;
						</div>
					</div>
				</div>
			</div>

			<div class="hr-line-dashed"></div>

			<div class="form-group">
				<label class="col-sm-2 control-label">详细介绍：</label>
				<div class="col-sm-10">
					<input id="intro" name="intro" type="hidden">
					<div class="summernote"></div>
				</div>
			</div>

		</form>
	</div>
	<div th:include="include::footer"></div>
	<th:block th:include="include :: bootstrap-fileinput-js" />
	<th:block th:include="include :: summernote-js" />
	<th:block th:include="include :: bootstrap-select-js" />
	<script th:inline="javascript">
		var prefix = ctx + "goods/goods"
		$("#form-goods-add").validate({
			rules: {
				xxxx: {
					required: true,
				},
			},
			focusCleanup: true
		});

		function submitHandler() {
			if ($.validate.form()) {
				var sHTML = $('.summernote').summernote('code');
				$("#intro").val(sHTML);
				$.operate.save(prefix + "/add", $('#form-goods-add').serialize());
			}
		}

		/*用户管理-新增-选择部门树*/
		function selectGoodsTree() {

			// console.log("tree");
			var treeId = $("#treeId").val();
			var catId = $.common.isEmpty(treeId) ? "100" : $("#treeId").val();
			var url = ctx + "goods/goodsCat/selectCatTree/" + catId;
			// console.log("url:",url);
			var options = {
				title: '选择分类',
				width: "380",
				url: url,
				callBack: doSubmit
			};
			$.modal.openOptions(options);
		}

		function doSubmit(index, layero) {
			var tree = layero.find("iframe")[0].contentWindow.$._tree;
			if ($.tree.notAllowParents(tree)) {
				var body = layer.getChildFrame('body', index);
				$("#treeId").val(body.find('#treeId').val());
				$("#treeName").val(body.find('#treeName').val());
				layer.close(index);

				var typeId = body.find('#typeId').val();
				//设置商品的类型
				$("#typeId").val(typeId);
				// console.log("typeName:", body.find('#typeName').val())
				$("#typeName").val(body.find('#typeName').val());

				//设置品牌
				resetBrandSelect(typeId);
				//查找类型是否有关联扩展属性和规格
				resetProps(typeId);
			}
		}

		function resetBrandSelect(typeId) {
			$('[data-role="brand"]').empty('');
			$.ajax({
				url: ctx + "goods/brand/brandListByTypeId",
				type: 'POST',
				data: {
					typeId: typeId
				},
				success: function (result) {
					if (result.code == web_status.SUCCESS) {
						// console.log(result.data);
						if (result.data.lenth == 0) {
							return;
						}
						$('[data-role="brand"]').append('<option value="">请选择品牌</option>');
						$.each(result.data, function (index, item) {
							$('[data-role="brand"]').append('<option value="' + item.brandId + '">' + item
								.brandName + '</option>');
						});
						$('[data-role="brand"]').selectpicker("refresh");
					}
				}
			});
		}

		function resetProps(typeId) {
			$.ajax({
				url: ctx + "goods/goodsType/getPropsAndSpecs",
				type: 'POST',
				data: {
					typeId: typeId,
					goodsId: $("#goodsId").val()
				},
				success: function (result) {
					$("#propsDiv").empty('');
					if (result.code == web_status.SUCCESS) {
						if (result.data.specIdList.length > 0) {
							//设置开启规格按钮
							$("#specBtn").show();
						}else {
							$("#specBtn").hide();
						}

						if (result.data.lenth == 0) {
							return;
						}

						$.each(result.data.typePropsList, function (index, item) {
							// console.log(item.name)
							// console.log(item.typePropsValueList)

							var prop = "p" + (index + 1);
							var value = result.data.goods[prop];
							var select = buildSelect(item.name, prop, item.typePropsValueList, value);
							// console.log("select:",select)
							$("#propsDiv").append(select);
						});
					}
				}
			});
		}

		//动态添加下拉框
		function buildSelect(label, name, options, value) {

			var value = value || "";
			var select = '<div class="row">\
						<div class="col-md-6">\
							<div class="form-group">\
								<label class="col-sm-3 control-label"><span style="color: red; ">*</span>' + label + '：</label>\
								<div class="col-sm-9">\
									<select id="' + name + '" name="' + name + '"class="form-control noselect2"  required>\
										<option value="">请选择属性</option>';

			for (var i = 0; i < options.length; i++) {
				select += '<option value="' + options[i].propsValueId + '"' + (value == options[i].propsValueId ? "selected" :
					"") + '>' + options[i].name + '</option>';
			}

			select += '</select>\
							</div>\
						</div>\
			      </div>\
			  </div>';
			return select;
		}


		$(function () {

			$("#goodsPicture").fileinput({
				// 'theme': 'gly',
				uploadUrl: ctx + "common/upload",
				// deleteUrl: ctx + "common/delete",
				showRemove: false,
				overwriteInitial: false,
				initialPreviewAsData: true,
				initialPreview: [
					// "http://localhost:8087/profile/upload/2019/06/24/c2d677281d4be44f059b82fc9a3d180f.png"
				]
			}).on("fileuploaded", function (event, result) {
				var flag = $('.file-preview-success').hasClass('is-selected');
				var imageIds = $('#imageIds').val();
				var imageId = result.response.data[0].imageId;

				if(!flag){
					$('.file-preview-success').eq(0).addClass('is-selected');
				}

				if(imageIds !="" && imageIds != null){
					imageIds = imageIds+","+result.response.data[0].imageId;
				}else {
					imageIds = result.response.data[0].imageId
				}
				$('#imageDefaultId').val(imageId);
				$('#imageIds').val(imageIds);
			}).on("filepredelete", function(jqXHR) {
                var abort = true;
                if ($.modal.confirm("您确认要删除该图片么?"),function () {
                    abort = false;
                })
                return abort; // you can also send any data/object that you can receive on `filecustomerror` event
            });

		});


		//点击切换默认图
		$(document).on('click', '.kv-file-content', function (e) {
			var flag = $(this).parent().hasClass('is-selected');
			if(flag){
				console.log("删除默认图")
			}else {
				console.log("删除非默认图")
				$(this).parent().addClass('is-selected').siblings().removeClass('is-selected');
				var index = $(this).index();

				var chosedVal = $('#imageIds').val().split(',')[index];
				$('#imageDefaultId').val(chosedVal);
			}
			// $.modal.confirm("确认更换默认图片吗？", function() {
			// });
			return false;
		})

		//删除默认图的时候如果有其他图，设置其他图有默认图，如果没有则清空


		//初始化fileinput控件（第一次初始化）
		function initFileInput(ctrlName, uploadUrl, count, deleteUrl, deleteExtraData) {
			var control = $('#' + ctrlName);
			control.fileinput({
				uploadUrl: uploadUrl,
				deleteUrl: deleteUrl,
				maxFileCount: 6,
				showRemove: false, // 是否显示移除按钮
				enctype: 'multipart/form-data',
				overwriteInitial: false,
				initialPreviewAsData: true,
				allowedFileExtensions: ['jpg', 'png', 'gif'], //接收的文件后缀,
				msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
				'theme': 'explorer-fas',
				initialPreview: [
					// "/img/profile.jpg"
				]
			});
		}



		$('.summernote').summernote({
			placeholder: '请输入内容',
			height: 192,
			lang: 'zh-CN',
			followingToolbar: false,
			callbacks: {
				onImageUpload: function (files) {
					sendFile(files, this);
				}
			}
		});

		// 上传文件
		function sendFile(files, obj) {
			var formData = new FormData();
			for (f in files) {
				formData.append("file", files[f]);
			}

			$.ajax({
				type: "POST",
				url: ctx + "common/upload",
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				dataType: 'json',
				success: function (result) {
					if (result.code == web_status.SUCCESS) {
						$.each(result.data, function (i, item) {
							$(obj).summernote('editor.insertImage', item.url, item.fileName);
						});
					} else {
						$.modal.alertError(result.msg);
					}
				},
				error: function (error) {
					$.modal.alertWarning("图片上传失败。");
				}
			});
		}

		//开启商品规格
		$("#btnAdd").on("click", function () {
			//货号 库存 价格 货位
			var bn = $("#bn").val();
			var store = ($("#store").val() == '' ? 0 : $("#store").val());
			var price = ($("#price").val() == '' ? 0 : $("#price").val());
			var storePlace = $("#storePlace").val();

			var url = ctx + "goods/products/addProductSku?typeId=" + $("#typeId").val() + "&bn=" + bn +
				"&store=" + store + "&price=" + price + "&price=" + price + "&storePlace=" + storePlace;

			// console.log(url)
			var options = {
				title: '商品规格',
				width: 900,
				url: url,
				btn: ['关闭'],
				yes: function (index) {
					layer.close(index);
				}
			};
			$.modal.openOptions(options);

		});




		//重新编辑商品规格
		$('[data-role="product-close"]').on("click", function () {
			$.modal.confirm("确定要关闭规格么?", function () {
				$("#specDesc").val("");
				$("#specBtn").show(); //显示规格按钮
				$("#specDiv").hide(); //隐藏规格编辑信息
				$("#goodsBasic").show(); //显示商品价格等信息
			});
		});

		function setSpecDesc(specDesc) {
			$("#specDesc").val(specDesc);
			editProductInfo(specDesc);
			$("#specBtn").hide(); //隐藏规格按钮
			$("#specDiv").show(); //显示规格编辑信息
			$("#goodsBasic").hide(); //隐藏商品价格等信息
		}

		function editProductInfo(specDesc) {
			//编辑货品
			$("#specDiv").show()
			$('[data-role="spec-item"]').html("");
			$('[data-role="spec-tit"]').html("");
			var jsonSpecDesc = JSON.parse(specDesc);
			// console.log(jsonSpecDesc)
			var specNameArr = jsonSpecDesc.specNames.split(",")

			$('[data-role="spec-item"]').append('<li class="tit">已经启动的规格项:</li>');
			$.each(specNameArr, function (i, item) {
				$('[data-role="spec-item"]').append("<li>" + item + "</li>");
			});

			var result = '<p class="tit" data-role="spec-tit">已生成货品(' + jsonSpecDesc.num + ')</p>';
			$('[data-role="spec-tit"]').append(result)
		}
	</script>
</body>

</html>